function PhysicsObject() {
}

PhysicsObject.prototype.elasticity = 0.5;
PhysicsObject.prototype.stickiness = 2;
PhysicsObject.prototype.d = [0,0];


function update() {
    for (var i = 0; i < dynamic_objects.length; i++) {
        var d = dynamic_objects[i];
        d.stuck = false;
        for (var j = 0; j < static_objects.length; j++) {
            var o = static_objects[j];
            if (d === o) continue;
            var val = o.will_collide(d);
            if (val[0]) {
				var decomp = normalDecompose(d.d, val[1]);
                if (o.is_solid()) {
                    d.collide(val[1], decomp, o.elasticity, Math.max(params.minStickiness, o.stickiness));
                }
				if (o.glObject) {
					o.glObject.collide(val[1], decomp, val[2]);
				}
                o.trigger(d);
            }
        }
    }

    for (var i = 0; i < objects.length; i++) {
        var d = objects[i];
        d.update();
        if (d.glObject) {
            d.glObject.update();
        }
    }
}

PhysicsObject.prototype.will_collide = function(other) {
    var poly = this.boundary;
    for (var i = 1; i < poly.length; i++) {
        var v = other.will_collide_line(add(this.p, poly[i - 1]), add(this.p, poly[i]));
        if (v[0]) {
            return v;
        }
    }
    return [false, [0, 0], [0, 0]];
}

PhysicsObject.prototype.will_collide_line_internal = function(pt0, pt1) {
    throw 0;
}

function lineIntersect(a, b, c, d) {
    var detab = det(a, b);
    var detcd = det(c, d);
    var cd = sub(c, d);
    var ab = sub(a, b);
    var detabcd = det(ab, cd);
    return scale(1/detabcd, sub(scale(detab, cd), scale(detcd, ab)));
}

PhysicsObject.prototype.will_collide_line = function(pt0, pt1) {
    if (this.will_collide_line_internal(pt0, pt1)) {
        var normal = [pt0[1] - pt1[1], -(pt0[0] - pt1[0])];
        if (dot(this.d, normal) > -0.001) return false;
        normalize(normal, 1);
        var pos = lineIntersect(pt0, pt1, this.p, add(this.p, this.d));
        return [true, normal, pos];
    }
    return [false, [0, 0], [0, 0]];
}

PhysicsObject.prototype.collide = function(normal, decomp, elasticity, stickiness) {
    var dotn = decomp[0], ncomp = decomp[1], tcomp = decomp[2];

    if (length(ncomp) < stickiness) {
        ncomp = [0, 0];
        this.stuck_to = normal;
        this.stuck = true;
    }

    ncomp = scale(-elasticity, ncomp);
    this.d = add(ncomp, tcomp);
}

PhysicsObject.prototype.update = function() {
    this.move();
}

PhysicsObject.prototype.move = function() {
    for (var i = 0; i < this.p.length; i++) {
        this.p[i] += this.d[i];
    }
}

PhysicsObject.prototype.is_solid = function() {
    return true;
}

PhysicsObject.prototype.trigger = function(obj) {
}



